package com.heima.kafka;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.junit.Test;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class KafkaStreamQuickStart {

    @Test
    public void testKafaStream(){
        //3. 完成kafa的相关配置
        Properties prop = new Properties();
        prop.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        prop.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.APPLICATION_ID_CONFIG, "testKafaStream");

        //2. 构建StreamBulider的对象
        StreamsBuilder streamsBuilder = new StreamsBuilder();

        streamProcessor(streamsBuilder);
        //1. 创建KafkStream的核心对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), prop);

        kafkaStreams.start();

        while (true){}
    }

    private void streamProcessor(StreamsBuilder streamsBuilder) {
        //1. 订阅一个主题
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");

        //2. 处理消息并把结果写到一个新的主题中
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                System.out.println(value);
                return Arrays.asList(value.split(" "));
            }
        }).groupBy((key, value) -> value)
                .windowedBy(TimeWindows.of(Duration.ofSeconds(5)))
                .count()
                .toStream()
                .map((key, value) -> {
                    System.out.println(key + " : " + value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                .to("itcast-topic-out");

    }
}
